package com.smart.village.big.screen.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.smart.village.big.screen.service.ChinaMobileSmsService;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.security.MessageDigest;
import java.util.Base64;
import java.util.logging.Logger;

@Service
public class ChinaMobileSmsServiceImpl implements ChinaMobileSmsService {
    java.util.logging.Logger logger = Logger.getLogger(ChinaMobileSmsServiceImpl.class.getName());
    @Value("${china.mobile.mas.ec-name}")
    private String ecName;
    @Value("${china.mobile.mas.ap-id}")
    private String apId;
    @Value("${china.mobile.mas.secret-key}")
    private String secretKey;
    @Value("${china.mobile.mas.sign}")
    private String sign;
    @Value("${china.mobile.mas.add-serial}")
    private String addSerial;
    @Value("${china.mobile.mas.send-url}")
    private String sendUrl;

    @Override
    public JSONObject sendSms(String mobile, String content) {
        HttpClient client = HttpClient.newHttpClient();

        String encode = buildParams(mobile,content);

        // HTTP客户端向云MAS平台发送短信任务请求，云MAS平台接收到请求后验证数据，验证通过将数据发送给短信网关
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(sendUrl))
                .POST(HttpRequest.BodyPublishers.ofString(encode))
                .build();
        HttpResponse<String> response = null;
        try {
            response = client.send(request, HttpResponse.BodyHandlers.ofString());
        } catch (java.io.IOException | InterruptedException e) {
        logger.info("sendSms, response: " + response.body());
            e.printStackTrace();
        }
        if (response != null) {
            logger.info("sendSms, response:" + response.body());
        }
        if (response != null) {
            return JSONObject.parseObject(response.body());
        }
        return null;
    }

    private String buildParams(String mobiles,String content){

        JSONObject params = new JSONObject();
        params.put("ecName",ecName);
        params.put("apId",apId);
        params.put("secretKey",secretKey);
        params.put("sign",sign);
        params.put("addSerial",addSerial);
        params.put("mobiles",mobiles);
        // json字符串转换为JSONObject对象，为了将特殊字符进行转义
        JSONObject contentJson = new JSONObject();
        contentJson.put("content",content);

        String jsonString = contentJson.toJSONString();
        JSONObject contentObj = JSONObject.parseObject(jsonString);

        params.put("content",contentObj.getString("content"));

        StringBuilder sb = new StringBuilder();
        sb.append(ecName);
        sb.append(apId);
        sb.append(secretKey);
        sb.append(mobiles);
        sb.append(contentObj.getString("content"));
        sb.append(sign);
        sb.append(addSerial);
        // 计算 MD5（32位小写）
        String selfMac =  encryptToMD5(sb.toString());
        params.put("selfMac",selfMac);
        logger.info("selfMac====================="+selfMac);

        String paramsJSONString = params.toJSONString();
        logger.info("paramsJSONString====================="+paramsJSONString);

        String encode = Base64.getEncoder().encodeToString(paramsJSONString.getBytes());
        logger.info("encode====================="+encode);

        return encode;
    }

    private String encryptToMD5(String string) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] array = md.digest(string.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : array) {
                sb.append(Integer.toHexString((b & 0xFF) | 0x100).substring(1, 3));
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
